package com.zzy.chapter4.strategy.factory;

import cn.hutool.extra.spring.SpringUtil;
import com.zzy.chapter4.strategy.PayStrategyInterface;
import com.zzy.chapter4.strategy.context.PayContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class PayContextFactory extends AbstractPayContextFactory<PayContext>{

    /**
     * 缓存策略对象：享元模式
     */
    private static final Map<String, PayContext> PAY_CONTEXTS = new ConcurrentHashMap<>();

    @Override
    public PayContext getContext(Integer payType) {
        PayStrategyEnum payStrategyEnum =
                payType == 1 ? PayStrategyEnum.WECHAT_PAY :
                payType == 2 ? PayStrategyEnum.ALIPAY : null;
        if(payStrategyEnum == null) {
            throw new RuntimeException("支付方式不存在");
        }
        PayContext payContext = PAY_CONTEXTS.get(payStrategyEnum.name());
        if(payContext == null) {
            try {
                PayStrategyInterface payStrategy = (PayStrategyInterface) Class.forName(payStrategyEnum.getValue()).newInstance();
                PayContext context = new PayContext(payStrategy);
                PAY_CONTEXTS.put(payStrategyEnum.name(), context);
                return context;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
